package com.apartmentManage.controller;

import com.apartmentManage.entity.Admin;
import com.apartmentManage.service.AdminService;
import com.apartmentManage.until.LoginResponse;
import com.apartmentManage.until.Renter;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AdminController {

    @Autowired
    private AdminService service;

    @PostMapping("/admin")
    public String getByRequirement(Admin admin, Model model){
        boolean flag = service.getByRequirement(admin);
        if (flag)
            LoginResponse.map.put("ADMIN",admin.getAccountName());
        Renter renter = new Renter(flag, flag ? "登录成功^_^" : "登陆失败-_-");
        model.addAttribute("renter",renter);
        model.addAttribute("AdminName",admin.getAccountName());
        if (flag)
            return "pages/index";
        return "AdminLogin";

    }
    @GetMapping("/test")
    public String test(){
        return "pages/apartmentTutor/add";
    }

    @GetMapping("/login")
    public String login(Model model){
        Renter renter = new Renter(true);
        model.addAttribute("renter",renter);
        return "AdminLogin";
    }


    @GetMapping("/registerView")
    public String registerView(Model model){
        Renter renter = new Renter(true);
        model.addAttribute("renter",renter);
        return "register";
    }


    @PostMapping("/register")
    public String save(Admin admin,Model model,String againPassword){
        boolean flag = service.save(admin,againPassword);
        Renter renter = new Renter(flag, flag ? "注册成功^_^ 请登录" : "注册失败-_-");
        model.addAttribute("renter",renter);
        if (flag)
            return "AdminLogin";
        return "register";
    }

    @PostMapping("updateByOldPassword")
   public String updateByOldPassword(Admin admin){
        boolean flag = service.updateByOldPassword(admin);
        if (flag)
            return "redirect:/img/On.html";
        return "redirect:updateByOldPasswordView/"+admin.getAccountName();
    }

    @GetMapping("updateByOldPasswordView/{adminName}")
    public String updateByOldPassword(@PathVariable String adminName, Model model){
        model.addAttribute("adminName",adminName);
        return "updateByOldPassword";
    }

    @GetMapping("/outLogin")
    public String  outLogin(){
        LoginResponse.map.remove("ADMIN");
        return "AdminLogin";
    }
}
